/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.grant.department.impl;

import com.beust.jcommander.internal.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.grant.department.RbacGrantDepartmentPluginPermissionService;
import com.je.rbac.service.permission.GrantMethodEnum;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.template.PcPluginBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RbacGrantDepartmentPluginPermissionServiceImpl implements RbacGrantDepartmentPluginPermissionService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private PcPluginBaseService pcPluginBaseService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveDepartmentPluginPermission(String departmentId, String pluginCode, GrantTypeEnum grantType) {
        List<DynaBean> pluginBasePermissionList = new ArrayList<>();
        pluginBasePermissionList.add(pcPluginBaseService.writePcPluginShowPermission(pluginCode, true));
        saveDeptPermAssocaition(departmentId, pluginBasePermissionList, grantType);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removeDepartmentPluginPermission(String departmentId, String pluginCode, GrantTypeEnum grantType) {
        List<String> menuPermissionList = new ArrayList<>();
        menuPermissionList.add(pcPluginBaseService.formatPcPluginShowTemplate(pluginCode));
        List<DynaBean> rolePermList = metaService.select("JE_RBAC_VDEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .in("PERM_CODE", menuPermissionList));
        List<String> menuPermissionIdList = new ArrayList<>();
        for (DynaBean eachRolePermBean : rolePermList) {
            menuPermissionIdList.add(eachRolePermBean.getStr("JE_RBAC_DEPTPERM_ID"));
        }
        metaService.delete("JE_RBAC_DEPTPERM", ConditionsWrapper.builder().in("JE_RBAC_DEPTPERM_ID", menuPermissionIdList));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveDepartmentPluginPermissions(String departmentId, List<String> pluginCodeList, GrantTypeEnum grantType) {
        List<DynaBean> allPermmissionBeanList = new ArrayList<>();
        for (String pluginCode : pluginCodeList) {
            allPermmissionBeanList.add(pcPluginBaseService.writePcPluginShowPermission(pluginCode,true));
        }
        saveDeptPermAssocaition(departmentId, allPermmissionBeanList, grantType);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removeDepartmentPluginPermissions(String departmentId, List<String> pluginCodeList, GrantTypeEnum grantType) {
        List<String> menuPermissionList = new ArrayList<>();
        for (String pluginCode : pluginCodeList) {
            menuPermissionList.add(pcPluginBaseService.formatPcPluginShowTemplate(pluginCode));
        }
        List<DynaBean> rolePermList = metaService.select("JE_RBAC_VDEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .in("PERM_CODE", menuPermissionList));
        List<String> menuPermissionIdList = new ArrayList<>();
        for (DynaBean eachRolePermBean : rolePermList) {
            menuPermissionIdList.add(eachRolePermBean.getStr("JE_RBAC_DEPTPERM_ID"));
        }
        metaService.delete("JE_RBAC_DEPTPERM", ConditionsWrapper.builder().in("JE_RBAC_DEPTPERM_ID", menuPermissionIdList));
    }

    /**
     * 保存关系
     *
     * @param deptId
     * @param permissionList
     */
    private void saveDeptPermAssocaition(String deptId, List<DynaBean> permissionList, GrantTypeEnum grantType) {
        //查询已存在的关联关系
        List<String> permissionIdList = new ArrayList<>();
        for (DynaBean eachPermissionBean : permissionList) {
            permissionIdList.add(eachPermissionBean.getStr("JE_RBAC_PERM_ID"));
        }
        Set<String> extendDepartmentIdList = rbacDepartmentService.findExtendIds(Lists.newArrayList(deptId));
        extendDepartmentIdList.add(deptId);
        List<DynaBean> associationList = metaService.select("JE_RBAC_DEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .in("JE_RBAC_DEPARTMENT_ID", extendDepartmentIdList)
                .in("JE_RBAC_PERM_ID", permissionIdList));
        List<String> havedRolePermissionList = new ArrayList<>();
        for (DynaBean eachAssociationBean : associationList) {
            havedRolePermissionList.add(eachAssociationBean.getStr("JE_RBAC_PERM_ID"));
        }

        //写入关联关系
        DynaBean rolePermBean;
        for (DynaBean eachPermissionBean : permissionList) {
            //如果是正常权限，不是排他权限，则不做任何处理，如果是排他权限，则需要设置ROLEPERM_NOT_CHECKED
            if (havedRolePermissionList.contains(eachPermissionBean.getStr("JE_RBAC_PERM_ID"))) {
                continue;
            }

            rolePermBean = new DynaBean("JE_RBAC_DEPTPERM", false);
            rolePermBean.set("JE_RBAC_DEPARTMENT_ID", deptId);
            rolePermBean.set("JE_RBAC_PERM_ID", eachPermissionBean.getStr("JE_RBAC_PERM_ID"));
            rolePermBean.set("DEPTPERM_EXCLUDE_CODE", "0");
            rolePermBean.set("DEPTPERM_EXCLUDE_NAME", "否");
            //授权方式
            rolePermBean.set("DEPTPERM_TYPE_CODE", GrantMethodEnum.ROLE.name());
            rolePermBean.set("DEPTPERM_TYPE_NAME", GrantMethodEnum.ROLE.getDesc());
            //授权类型
            rolePermBean.set("DEPTPERM_GRANTTYPE_CODE", grantType.name());
            rolePermBean.set("DEPTPERM_GRANTTYPE_NAME", grantType.getDesc());
            //todo 设置租户信息
            commonService.buildModelCreateInfo(eachPermissionBean);
            metaService.insert(rolePermBean);
        }
    }

}
